package com.kaka.bus.engine.borrow.idcard;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.kaka.bus.AppCenter;
import com.kaka.bus.R;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.IDCardFrontBean;
import com.kaka.bus.bean.Lianxi;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.constant.UserConstant;
import com.kaka.bus.engine.home.main.limit.LimitActivity;
import com.kaka.bus.listener.Listener;
import com.kaka.bus.manager.Result;
import com.kaka.bus.manager.T;
import com.kaka.bus.util.Base64En;
import com.kaka.bus.util.U;
import com.kaka.bus.util.logger.Logger;
import com.kaka.bus.view.GlideOval;
import com.megvii.idcardquality.IDCardQualityLicenseManager;
import com.megvii.licensemanager.Manager;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.HashSet;

import butterknife.BindView;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableOnSubscribe;

/**
 * Created by zhangqi on 2016/10/19.
 * e-mail : ${email}
 * desc :
 */

public class IdCardBackActivity extends BaseActivity<IdCardPresenter> implements IdCardContract.View {


    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_back_office)
    TextView mTvBackOffice;
    @BindView(R.id.tv_back_validity)
    TextView mTvBackValidity;
    @BindView(R.id.btn_back_commit)
    AppCompatButton mBtnBackCommit;
    @BindView(R.id.btn_back_re)
    AppCompatButton mBtnBackRe;
    RxPermissions mRxPermissions;

    private int mRequestCode = 100;
    private IDCardFrontBean mIDCard;
    private String mPhoto;
    private int mBack = 104;
    private boolean mIsGoBack;
    /**
     * 是否拍过照片
     */
    private boolean mIsCheck;

    @Override
    protected void initView() {
        super.initView();
        mToolbarName.setText("身份证反面照");
        mToolbarBack.setOnClickListener(v -> finish());

        mRxPermissions = new RxPermissions(this);

    }

    @Override
    protected void initListener() {
        /**
         * 6.0摄像头权限校验
         */
        mIvBack.setOnClickListener(v -> {
            mRxPermissions
                    .request(Manifest.permission.CAMERA)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            goCamera();
                        } else {
                            /**
                             * 拒绝
                             */
                            AppCenter.mSpUtil.putBoolean(UserConstant.CAMERA_PERMISSION, aBoolean);
                            showMessage("您拒绝了相机权限,请到设置里开启相机权限");
                        }
                    });
        });
        mBtnBackRe.setOnClickListener(v -> {
            mRxPermissions
                    .request(Manifest.permission.CAMERA)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            goCamera();
                        } else {
                            /**
                             * 拒绝
                             */
                            AppCenter.mSpUtil.putBoolean(UserConstant.CAMERA_PERMISSION, aBoolean);
                            showMessage("您拒绝了相机权限,请到设置里开启相机权限");
                        }
                    });
        });
        /**
         * 提交信息
         */
        mBtnBackCommit.setOnClickListener(v -> {
            if (mIsCheck) {
                mPresenter.sendService(getUserId(), getToken(), mIDCard, mPhoto, mBack);
            } else {
                showMessage("请先扫描身份证");
            }
        });
    }

    public void goCamera() {
        showDialog("联网授权中...");
        String uuid = System.currentTimeMillis()+"";

        Flowable.create((FlowableOnSubscribe<Integer>) e -> {
            Manager manager = new Manager(this);
            IDCardQualityLicenseManager idCardLicenseManager = new IDCardQualityLicenseManager(this);
            manager.registerLicenseManager(idCardLicenseManager);
            manager.takeLicenseFromNetwork(uuid);
            if (idCardLicenseManager.checkCachedLicense() > 0)
                e.onNext(1);
            else
                e.onNext(2);
        }, BackpressureStrategy.BUFFER)
                .compose(T.D())
                .subscribeWith(new Result<Integer>() {
                    @Override
                    protected void onSuccess(Integer result) {
                        dissDialog();
                        if(result == 1){
                            Intent intent = new Intent(IdCardBackActivity.this,
                                    com.megvii.idcardlib.IDCardScanActivity.class);
                            intent.putExtra("side", 1);
                            intent.putExtra("isvertical", false);
                            startActivityForResult(intent, mBack);
                        }else if(result == 2){
                            showMessage("联网授权失败!请重新");
                        }
                    }
                });
    }

    @Override
    public void sendFailed(int type) {
        switch (type) {
            case UserConstant.TOKEN_OUT:
               U.tokenOut(this);
                break;
            case 0:
                setError("请重新拍摄!");
                break;
        }
    }

    @Override
    public void sendSuccess(HttpWrapper<String> bean) {
        if(Constant.SUCCESS_CODE.equals(bean.code)){
            mRxPermissions.request(Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            uploadContact();
                        } else {
                            U.getSingleDialog(this, "温馨提示", "您已经拒绝了权限,请在设置-应用管理中打开读取通讯录权限", "了解", null).show();
                        }
                    });
        }else if(Constant.ERROR_CODE.equals(bean.code)){
            showMessage(bean.info);
        }else if(Constant.TOKEN_TIMEOUT.equals(bean.code)){
            U.tokenOut(this);
        }
    }

    @Override
    public void setInfo(byte[] data, IDCardFrontBean idCard) {

        //TODO
        mIsCheck = true;
        mTvBack.setVisibility(View.GONE);
        mTvBackOffice.setVisibility(View.VISIBLE);
        mTvBackValidity.setVisibility(View.VISIBLE);
        mIDCard = idCard;

        mPhoto = new String(Base64En.base64Encode(data));
        Glide.with(this)
                .load(data).transform(new GlideOval(this))
                .into(mIvBack);

        String vaild_priod = idCard.getValid_date();

        mTvBackOffice.setText("签发机关 : "+idCard.getIssued_by());
        mTvBackValidity.setText("有效期 : "+vaild_priod);

        mBtnBackRe.setText("重拍");
    }

    @Override
    public void setError(String info) {
        U.getSingleDialog(this,"温馨提示",info,"确定",null).show();
        mIvBack.setVisibility(View.VISIBLE);
    }

    @Override
    public void reTakePhoto() {
        U.getSlectDialog(this, "温馨提示", "扫描照片质量过低,请重新拍摄", "取消", "重拍", new Listener.OnNormalAlertDialogChooseClickListener() {
            @Override
            public void onLeft() {

            }

            @Override
            public void onRight() {
                goCamera();
            }
        }).show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPresenter.sendPic(resultCode, data,mBack,getUserId(),getToken());
    }

    /**
     * 上传通讯录
     */
    private void uploadContact() {
        new Thread(){
            @Override
            public void run() {
                HashSet<Lianxi> allContactInfo = U.queryContacts(IdCardBackActivity.this);
                if(allContactInfo.size() == 0){
                    runOnUiThread(() -> U.getSlectDialog(IdCardBackActivity.this, "提示", "通讯录为空读取通讯录权限可能被拒绝,请先开启权限", "取消", "前去设置",
                            new Listener.OnNormalAlertDialogChooseClickListener() {
                                @Override
                                public void onLeft() {

                                }

                                @Override
                                public void onRight() {
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    Uri uri = Uri.fromParts("package", IdCardBackActivity.this.getPackageName(), null);
                                    intent.setData(uri);
                                    IdCardBackActivity.this.startActivity(intent);
                                }
                            }).show());
                    return;
                }

                String json = new Gson().toJson(allContactInfo);
                Logger.i("联系人提交的信息"+allContactInfo.size() + "---" + json);
                mPresenter.uploadContact(getUserId(),json);
            }
        }.start();
    }

    @Override
    public void uploadContactSuccess(HttpWrapper<String> s) {
        if(Constant.SUCCESS_CODE.equals(s.code)){
            startActivity(new Intent(this, LimitActivity.class));
        }else{
            uploadContactFaild();
        }
    }

    @Override
    public void uploadContactFaild() {
        U.getSingleDialog(this, "温馨提示", "信息获取有误,请重新尝试","确定",null).show();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_idcardback;
    }
    @Override
    protected boolean needFullScreen() {
        return true;
    }
    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

}
